package com.sunhao.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sunhao.common.utils.HttpUtils;
import com.sunhao.common.utils.R;
import com.sunhao.gulimall.auth.feign.MemberFeignService;
import com.sunhao.common.vo.MemberRespVo;
import com.sunhao.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 描述：OAuth2Controller 类的用途 第三方登录controller
 * 日期：2025/1/6
 */
//ums_member
@Slf4j
@Controller
public class OAuth2Controller {
    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session, HttpServletResponse servletResponse) throws Exception {
        Map<String,String> map = new HashMap<>();

        map.put("client_id","227634624");
        map.put("client_secret","0127e5f4e29a915644a5dfe97f7da674");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);

        //1.根据code换取token
        // HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), map, new HashMap<>());
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post",  new HashMap<>(), map, new HashMap<>());

        //2.处理
        if (response.getStatusLine().getStatusCode()==200)
        {
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //1.判断用户是否第一次使用
            R oauthlogin = memberFeignService.oauthlogin(socialUser);

            //成功
            if (oauthlogin.getCode()==0)
            {
                MemberRespVo data = oauthlogin.getData("data", new TypeReference<MemberRespVo>() {
                });
                log.info("登陆成功，用户信息：{}",data.toString());
                session.setAttribute("loginUser",data);
                return "redirect:http://gulimall.com";
            }
            else
            {
                return "redirect:http://auth.gulimall.com/login.html";
            }

        }
        else
        {
            return "redirect:http://auth.gulimall.com/login.html";
        }




    }
}
